package mju.cxf;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.UUID;

public class OssUtil {
    private static final Logger log = LoggerFactory.getLogger(OssUtil.class);
    private OSSEntry ossEntry;

    public void setOssEntry(OSSEntry ossEntry) {
        this.ossEntry = ossEntry;
    }

    public String setOss(MultipartFile file, String directory) throws IOException {
        String s = "";
        String originalFilename = file.getOriginalFilename();
        if (originalFilename != null) {
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            InputStream inputStream = file.getInputStream();
            OSS ossClient = new OSSClientBuilder().build(ossEntry.getEndpoint(), ossEntry.getKey(), ossEntry.getSer());
            try {

                String objectName = UUID.randomUUID() + substring;
                ossClient.putObject(ossEntry.getBucketName(), directory + objectName, inputStream);
                s = "http://" + ossEntry.getBucketName() + "." + ossEntry.getEndpoint().substring(ossEntry.getEndpoint().indexOf("o")) + "/" + directory + objectName;
                return s;
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
                return "error";
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
                return "error";
            } finally {
                ossClient.shutdown();
            }
        } else {
            return "error";
        }
    }


    public String deleteOss(String fileUrl) {
        // 解析 URL，提取 bucketName 和 objectName
        String bucketName = ""; // 存储桶名称
        String objectName = ""; // 文件在 OSS 中的完整路径

        // 根据您的 URL 格式解析存储桶名称和对象名称
        try {
            String[] urlParts = fileUrl.split("/");
            bucketName = urlParts[2].split("\\.")[0]; // 取到 bucketName
            objectName = String.join("/", Arrays.copyOfRange(urlParts, 3, urlParts.length)); // 取到 objectName
        } catch (Exception e) {
            System.out.println("解析 URL 时出错: " + e.getMessage());
            return "error";
        }
        OSS ossClient = new OSSClientBuilder().build(ossEntry.getEndpoint(), ossEntry.getKey(), ossEntry.getSer());
        try {
            // 删除对象
            ossClient.deleteObject(ossEntry.getBucketName(), objectName);

            return "success";
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorMessage());
            System.out.println("Error Code: " + oe.getErrorCode());
            System.out.println("Request ID: " + oe.getRequestId());
            System.out.println("Host ID: " + oe.getHostId());
            log.error("{}{}", oe.getMessage(), fileUrl);
            return "error";
        } catch (ClientException ce) {
            System.out.println("Caught a ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
            return "error";
        } finally {
            ossClient.shutdown();
        }
    }
}
